#!/usr/bin/env python
"""

Provides direct HTTP Fluffy data.

For more information, please see the documentation in README.txt, or simply
issue help() on any function or module contained within this package.

For license information, please see LICENSE.txt.


Author: Jake Lin
Initial Revision: 02/15/11

"""

# Imports

import cookielib
import os
import sys
from urlparse import urlparse
import urllib2
import urllib
try: import json #python 2.6 included simplejson as json
except ImportError: import simplejson as json
import addama.api
from config import *

def url_fix(s, charset='utf-8'):
    if isinstance(s, unicode):
        s = s.encode(charset, 'ignore')
    scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
    path = urllib.quote(path, '/%')
    qs = urllib.quote_plus(qs, ':&=')
    return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))

def processFluffyFile(dir, uri, limscookie):
	print "processing uri " + uri
	fluffy_data = addama.api.resource.getFile(uri.replace(" ", "%20"), limscookie)
	name = uri.split("/")[-1]
	localFile = open(dir + "/" + name, 'w')
	localFile.write(fluffy_data.read())
	localFile.close()

def processFluffyDir(url, limscookie, parent):
	print "Processing parent dir " + parent + " url " + url
	fluffyJson = addama.api.resource.getJSON((url + "/dir").replace(" ", "%20"), limscookie)
        currentDirName = url.split("/")[-1]
	if (not os.path.exists(parent + "/" + currentDirName)):
		os.makedirs(parent + "/" + currentDirName)

	if ("directories" in fluffyJson):
		fluffyDir = fluffyJson["directories"]
		#if (not os.path.exists(parent + "/" + currentDirName)):
		#	os.makedirs(parent + "/" + currentDirName)
	
        	for dir in fluffyDir:
                	print "directories " + dir["name"]
			processFluffyDir(dir["host-url"] + dir["uri"] , limscookie, parent + "/" + currentDirName)
        		
	if ("files" in fluffyJson):
		fluffyFiles = fluffyJson["files"]
		for fi in fluffyFiles:
                	processFluffyFile(parent + "/" + currentDirName,  url + "/" + fi["name"], limscookie)


# Function main
#  This is non-standard, and should not be confused with __main__, 
#  which indicates this script is called directly.
def _fmain():
	"""Function main: analog for the \"main\" function in other languages""" 
	url = None
	if len(sys.argv) > 1:
		url = sys.argv[1]

	# URL must be supplied on the command line
	if not url:
		raise ValueError

	# Open our cookie jar and import any existing cookies
	authCookies = cookielib.CookieJar()

	if os.path.exists(AUTH_COOKIES):
		authCookies = addama.api.auth.loadCookies(AUTH_COOKIES)

	# Scheme (eg. HTTP, HTTPS), host location, and path must be given
	given = urlparse(url)
	if given.scheme == '' or given.netloc == '' or given.path == '':
		raise ValueError
	print "Getting url %s" % url 
	processFluffyDir(url, authCookies, ".")   


# Initialization and Execution
# Direct invocation
if __name__ == "__main__":
    _fmain()

# Library invocation
# If included as part of a package, the caller is responsible for
# initialization and executing _fmain()
